package com.andy.common.extend

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextPaint
import android.util.Base64
import android.util.Log
import java.io.File
import java.security.MessageDigest

/**
 * 获取base64编码后的字符串
 *
 * @receiver String
 * @return String
 */
fun String?.toBase64String(): String {
    if (isNullOrEmpty()) {
        return ""
    }
    try {
        return Base64.encodeToString(toByteArray(charset("UTF-8")), Base64.DEFAULT)
    } catch (e: Exception) {
        Log.e("StringExt", e.message + e.stackTraceToString())
    }

    return ""
}

/**
 * base64解码
 *
 * @receiver String
 * @return String
 */
fun String?.decodeBase64String(): String {
    if (isNullOrEmpty()) {
        return ""
    }

    try {
        return String(Base64.decode(toByteArray(charset("UTF-8")), Base64.DEFAULT))
    } catch (e: Exception) {
        Log.e("StringExt", e.message + e.stackTraceToString())
    }

    return ""
}

/**
 * md5编码
 *
 * @receiver String
 * @return String
 */
fun String.md5() =
    MessageDigest.getInstance("md5")
        .digest(this.toByteArray()).joinToString("") { "%02x".format(it) }
        .lowercase()

/**
 * 文件路径对应文件是否存在
 *
 * @return true 表示存在
 */
fun String?.fileExists() = !this.isNullOrEmpty() && File(this).exists()

/**
 * 字符串显示宽度
 * @receiver String?
 * @param size Float 字体大小
 */
fun String?.width(size: Float): Float {
    if (isNullOrEmpty())
        return 0f

    val paint = TextPaint()
    paint.textSize = size
    return paint.measureText(this)
}


/**
 * 复制功能
 */
fun String?.copy(context: Context, onSuccess: (() -> Unit)? = null) {
    if (this.isNullOrEmpty()) {
        return
    }
    val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val mClipData = ClipData.newPlainText("label", this)
    manager.setPrimaryClip(mClipData)
    onSuccess?.invoke()
}


/**
 * 判断是否安装App
 */

@SuppressLint("QueryPermissionsNeeded")
fun String.isAppInstalled(context: Context): Boolean {
    val pm: PackageManager = context.packageManager
    val pInfo: List<PackageInfo> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        pm.getInstalledPackages(PackageManager.PackageInfoFlags.of(PackageManager.GET_ACTIVITIES.toLong() or PackageManager.GET_SERVICES.toLong()))
    } else {
        @Suppress("DEPRECATION")
        pm.getInstalledPackages(0)
    }
    for (i in pInfo.indices) {
        if (pInfo[i].packageName.equals(this)) {
            return true
        }
    }
    return false
}

fun String?.safeToInt(): Int {
    return this?.toIntOrNull() ?: 0
}

fun String?.safeToLong(): Long {
    return this?.toLongOrNull() ?: 0L
}

fun String?.safeToFloat(): Float {
    return this?.toFloatOrNull() ?: 0F
}

fun String?.safeToDouble(): Double {
    return this?.toDoubleOrNull() ?: 0.0
}

fun String?.safeToBoolean(): Boolean {
    return this?.toBoolean() ?: false
}

const val TAG = "Ancoding"

fun String?.logD() {
    Log.d(TAG, this ?: "null")
}

fun String?.logI() {
    Log.i(TAG, this ?: "null")
}

fun String?.logW() {
    Log.w(TAG, this ?: "null")
}

fun String?.logE() {
    Log.e(TAG, this ?: "null")
}
